package com.qf.filter;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * 自动登录的过滤器
 */
@WebFilter(value = "/jsp/login.jsp",dispatcherTypes = {DispatcherType.REQUEST}) //配置过滤规则dipatcherType属性 当浏览器地址栏直接访问jsp/loin.jsp进行过滤
public class AutologinFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("AutologinFilter初始化了...");
    }

    public void destroy() {
        System.out.println("AutologinFilter销毁了");
    }

    //过滤任务
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //处理请求相关的信息/以及响应相关的信息
        //ServletRequest/ServletResponse-->强转为具体的子接口
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //当前访问/jsp/login.jsp登录页面,获取浏览器携带过来的所有cookie数据
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            //不为空,有内容
            String content = null ;
            //遍历cookie数组
            for(Cookie cookie : cookies){
                //如果cookie对象获取的cookie名就是"autouser"
                if("autouser".equals(cookie.getName())){
                    //获取它的内容
                    content = cookie.getValue(); //%E4%B9%9D%E5%B0%BE%E5%A6%96%E7%8B%90%3De10adc3949ba59abbe56e057f20f883e
                }
            }
            if(content!=null){
                //有内容,上面加密内容--进行解码
                //jdk工具URLDecoder
                //静态方法:public static String decode(String s,String enc):参数1:内容 参数2:字符集格式
                 content = URLDecoder.decode(content, "utf-8");
                 System.out.println(content) ;
                //"昵称=密码"  =拆分
                String[] strs = content.split("=");
                //昵称 strs[0] ;  strs[1] :密码
                //调用UserService:业务接口
                UserService userService = new UserServiceImpl() ;
                User user = userService.login(strs[0], strs[1]);//登录功能

                if(user!=null){
                    //存在
                    request.getSession().setAttribute("user",user);
                    //重定向到 /jsp/index.jsp 前台主页
                    response.sendRedirect(request.getContextPath()+"/index");
                }else{
                    //放行
                    //内容为空.放行
                    chain.doFilter(request, response);
                }

            }else{
                //内容为空.放行
                chain.doFilter(request, response);
            }

        }else{
            //为空,没有内容,没有执行登录
            //放行
            chain.doFilter(request, response);
        }



    }
}
